package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.entity.SkuInfoEntity;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;


    @Autowired
    ThreadPoolExecutor executor;


    /**
     * Author : hmy
     *
     * @date 2021/9/19 13:48
     * desc : 利用线程池异步查询
     **/

    public CategoryEntity item(Long skuId) {
        CategoryEntity ce = new CategoryEntity();
        CompletableFuture<CategoryEntity> categoryEntityCompletableFuture = CompletableFuture.supplyAsync(() -> {
            CategoryEntity categoryEntity = this.baseMapper.selectById(skuId);
            return categoryEntity;
        }, executor);
        CompletableFuture<Void> future = categoryEntityCompletableFuture.thenAcceptAsync((res) -> {
            CategoryEntity item = this.item(res.getCatId());
            BeanUtils.copyProperties(item, ce);
        }, executor);
        return ce;
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * Author : hmy
     *
     * @date 2021/6/20 8:57
     * desc :   查询菜单的属性结构
     **/

    public List<CategoryEntity> listWithTree() {
        //1：查询所有的分类
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(null);

        //2:组装成父子的树形结构

        //2.1找到所有的一级分类
        List<CategoryEntity> collect = categoryEntities.stream().filter(x -> x.getParentCid() == 0)
                //设置子分类的属性
                .map((menu) -> {
                    menu.setChildren(getChildrens(menu, categoryEntities));
                    return menu;
                })
                .sorted((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()))
                .collect(Collectors.toList());
        return collect;
    }

    /**
     * Author : hmy
     *
     * @date 2021/6/20 9:12
     * desc :  递归查询所有的子菜单的查询方法
     * primes : 当前菜单，所有的菜单
     **/

    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> collect = all.stream().filter(x -> x.getParentCid().equals(root.getCatId())).map(
                (categoryEntity) -> {
                    categoryEntity.setChildren(getChildrens(categoryEntity, all));
                    return categoryEntity;
                }
                //排序
        ).sorted((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()))
                .collect(Collectors.toList());
        return collect;
    }

    /**
     * Author : hmy
     *
     * @date 2021/6/20 13:35
     * desc : 批量删除菜单信息
     **/
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 有引用的不能删除

        this.baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        List<Long> parentPath = this.findParentPath(catelogId, path);
        Collections.reverse(parentPath);
        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }


    //每一个需要缓存的数据我们都来指定要放到哪个名字的缓存，【缓存的分区（按照业务进行分区）】
//    @Cacheable(value = {"category"},key = "'getCategoryLevel1'")
//    @CacheEvict(value = {"category"},key = "'getCategoryLevel1'")
//    @Caching(evict = {
//            @CacheEvict(value = {"category"},key = "'getCategoryLevel1'"),
//            @CacheEvict(value = {"category"},key = "'getCatalogJson'")
//    })

    //    @CacheEvict(value = "category",allEntries = true)
    @Cacheable(value = {"category"}, key = "#root.method.name")
    @Override
    public List<CategoryEntity> getCategoryLevel1() {
        //查找所有的一级分类信息
        QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cat_level", 1);
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(queryWrapper);
        return categoryEntities;

    }

    /**
     * Author : hmy
     *
     * @date 2021/8/15 21:56
     * desc :
     **/

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        /**
         *  1: 空结果缓存，解决缓存击穿的问题
         *  2: 设置过期时间+随机值，解决缓存雪崩问题
         *  3：加锁，解决缓存击穿问题
         **/
        //1：加入缓存逻辑
        String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isEmpty(catalogJson)) {
            Map<String, List<Catelog2Vo>> catalogJsonDb = this.getCatalogJsonDbWithRedissonLock();
            String s = JSON.toJSONString(catalogJsonDb);
            stringRedisTemplate.opsForValue().set("catalogJson", s, 1, TimeUnit.DAYS);
            return catalogJsonDb;
        }
        Map<String, List<Catelog2Vo>> stringListMap = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return stringListMap;


    }

    /**
     * Author : hmy
     *
     * @date 2021/8/22 13:19
     * desc :  使用redisson实现分布式锁
     **/
    public Map<String, List<Catelog2Vo>> getCatalogJsonDbWithRedissonLock() {

        RLock lock1 = redissonClient.getLock("catalogJson-lock");
        lock1.lock();
        System.out.println("获取分布式锁成功。。。。。");
        Map<String, List<Catelog2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock1.unlock();
        }
        return dataFromDb;
    }


    /**
     * Author : hmy
     *
     * @date 2021/8/22 13:19
     * desc :  从数据库中查询并封装成分类数据，-   使用原生的set key value NX命令实现分布式锁
     **/
    public Map<String, List<Catelog2Vo>> getCatalogJsonDbWithSetRedisNxLock() {
        //1: 占用分布式锁
        String uuid = UUID.randomUUID().toString();
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        //设置过期时间
//        stringRedisTemplate.expire("lock",30,TimeUnit.SECONDS);
        if (aBoolean) { //加锁成功  执行业务
            System.out.println("获取分布式锁成功。。。。。");
            Map<String, List<Catelog2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            } finally {
                //2：执行完业务之后，记得删除锁，因为如果没有删除锁的话，那么别的实例再怎么通过自旋的方式也是无法实现获取锁的
//            String lock = stringRedisTemplate.opsForValue().get("lock");
//            if(lock.equals(uuid)){
//                stringRedisTemplate.delete("lock");
//            }
                //Lua脚本解锁
                String scrip = "if redis.call('get',KEYS[1]) == ARGV[1] then  return redis.call('del',KEYS[1])  else  return 0  end";
                Long lock = stringRedisTemplate.execute(new DefaultRedisScript<Long>(scrip, Long.class), Arrays.asList("lock"), uuid);
            }
            return dataFromDb;
        }
        System.out.println("获取分布式锁失败。。。等待重试");
        //加锁失败，重试的，因为加锁失败，我也要返回数据的，要不然导致这次查询会发生问题，而本地的synchronized也是自旋的方式进行重试的
        //如果重试的次数过高，那么可以休眠一段时间
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return getCatalogJsonDbWithSetRedisNxLock();  //通过调用自己实现自旋的方式
    }


    /**
     * Author : hmy
     *
     * @date 2021/8/15 21:42
     * desc : 从数据库查询并封装成分类数据  -- 使用本地锁
     **/
    public Map<String, List<Catelog2Vo>> getCatalogJsonDbWithLocalLock() {
        //加锁，只要是同一把锁，就能锁住，需要这个锁锁住所有的线程
        //this 就是当前对象， 所有的组件在容器中，都是单例的，因为这个CategoryServiceImpl都是只有一个实例对象，所以单个机器的情况下，这是能锁住的
        synchronized (this) {
            //得到锁之后，我们应该再去缓存中查询一次，如果有的话，直接返回，没有的话，就再去查询
            return getDataFromDb();
        }
    }


    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");
        if (!StringUtils.isEmpty(catalogJson)) {
            System.out.println("缓存命中，直接返回");
            Map<String, List<Catelog2Vo>> stringListMap = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return stringListMap;
        }
        System.out.println("缓存不命中，查询数据库");
        List<CategoryEntity> categoryEntities1 = baseMapper.selectList(null);
        //查询所有的分类信息
//        List<CategoryEntity> categoryLevel1 = this.getCategoryLevel1();
        List<CategoryEntity> categoryLevel1 = getParent_cid(categoryEntities1, 0L);
        Map<String, List<Catelog2Vo>> parent_cid = categoryLevel1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntities = getParent_cid(categoryEntities1, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (!CollectionUtils.isEmpty(categoryEntities)) {

                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<CategoryEntity> categoryEntity3List = getParent_cid(categoryEntities1, l2.getCatId());
                    if (!CollectionUtils.isEmpty(categoryEntity3List)) {

                        List<Catelog2Vo.Catelog3Vo> collect = categoryEntity3List.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        //3：将查询到数据放入到缓存中，将对象转为json放入到缓存中
        String s = JSON.toJSONString(parent_cid);
        stringRedisTemplate.opsForValue().set("catalogJson", s, 1, TimeUnit.DAYS);
        return parent_cid;
    }


    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            return Collections.EMPTY_LIST;
        }
        return collect;
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }

    private List<Long> findParentPath(Long catelogId, List<Long> path) {
        path.add(catelogId);
        CategoryEntity categoryEntity = this.baseMapper.selectById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(), path);
        }
        return path;
    }


}
